package fr.afcepf.ai85.gepeto.service;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.util.CalendarComparator;

import fr.afcepf.ai85.ent.Ecole;
import fr.afcepf.ai85.ent.Eleve;
import fr.afcepf.ai85.ent.MessageEnvoye;
import fr.afcepf.ai85.hibernate.util.HibernateUtil;

public class ServiceMessageEnvoye {

	public static List<MessageEnvoye> listeMessageEnvoye(Integer IdEnfant){		
		List<MessageEnvoye> liste=null;
		try
		{
			Session session = HibernateUtil.currentSession();
			Transaction tx = session.beginTransaction();
			Query hql = session.createQuery(
					"FROM MessageEnvoye as mes WHERE mes.eleve.idEleve like :idEl" );
			hql.setInteger("idEl", IdEnfant);			
			liste = hql.list();			
			tx.rollback();
			HibernateUtil.closeSession();
		}
		catch (Exception e) {
			// TODO: handle exception
			HibernateUtil.closeSession();
			e.printStackTrace();
		}
		return liste;		
	}
	
	public static String UnMessageEnvoye(Integer IdMessage){		
		List<MessageEnvoye> liste=null;
		String mess="";
		try
		{
			Session session = HibernateUtil.currentSession();
			Transaction tx = session.beginTransaction();
			Query hql = session.createQuery(
					"FROM MessageEnvoye as mes WHERE mes.idMessageEnvoye like :idMes" );
			hql.setInteger("idMes", IdMessage);			
			liste = hql.list();	
			
			if(liste.size()>0) mess=liste.get(0).getMessageEnv();
			
			tx.rollback();
			HibernateUtil.closeSession();
		}
		catch (Exception e) {
			// TODO: handle exception
			HibernateUtil.closeSession();
			e.printStackTrace();
		}
		return mess;		
	}

	
	public static void creerMessage(Integer IdEnfant,String objetMessage, String message){
//		
		ServiceEleveHib sh=new ServiceEleveHib();
		Eleve e=sh.rechercherEleveById(IdEnfant);		
		try {
			Session session = HibernateUtil.currentSession();
			Transaction tx = session.beginTransaction();
			Calendar cal=Calendar.getInstance();
			Date uneDate = cal.getTime();	
			MessageEnvoye m=new MessageEnvoye();
			m.setEleve(e);
			m.setMessageEnv(message);
			m.setObjetMessageEnv(objetMessage);
					
			session.save(m);
			tx.commit();
			HibernateUtil.closeSession();
		} catch (HibernateException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			System.out.println("erreur de creation du message");
		}
		
	}
	
	
	public static void main(String[] args) {
		creerMessage(12,"objetMes","unMess");
		
	}
}
